package server;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;

/**
 * 上下文
 */
public class Context extends BaseContainer<Wrapper> {
    private File contextDir;
    private String name;
    private Host host;

    private Context() {

    }

    /**
     * 根据 context 目录，构建 Context 实例
     * @param host
     * @param contextDir
     * @return
     * @throws Exception
     */
    public static Context build(Host host, File contextDir) throws Exception {
        Context context = new Context();
        context.contextDir = contextDir;
        context.name = contextDir.getName();
        context.host = host;
        context.init();
        return context;
    }

    public Wrapper getWrapper(String servletPath) {
        return getChild(servletPath);
    }

    public File getContextDir() {
        return contextDir;
    }

    public String getName() {
        return name;
    }

    public Host getHost() {
        return host;
    }

    /**
     * 初始化 context
     * @throws Exception
     */
    private void init() throws Exception {
        // 读取 web.xml 文件
        final File[] listWebXmlFile = contextDir.listFiles((file, name) -> "web.xml".equals(name));
        if (listWebXmlFile == null || listWebXmlFile.length == 0) {
            throw new Exception(String.format("Context [%s] 缺少 web.xml 文件", getName()));
        }
        File webXmlFile = listWebXmlFile[0];
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(webXmlFile);
        Element rootElement = document.getRootElement();

        // 解析 web.xml 中的 servlet 配置
        List<Element> selectNodes = rootElement.selectNodes("//servlet");
        for (int i = 0; i < selectNodes.size(); i++) {
            Element element = selectNodes.get(i);
            // <servlet-name>lagou</servlet-name>
            Element servletNameElement = (Element) element.selectSingleNode("servlet-name");
            String servletName = servletNameElement.getStringValue();
            // <servlet-class>server.LagouServlet</servlet-class>
            Element servletClassElement = (Element) element.selectSingleNode("servlet-class");
            String servletClass = servletClassElement.getStringValue();

            // 根据servlet-name的值找到url-pattern
            Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
            String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
            // 根据 servlet 配置，封闭 wrapper
            Wrapper wrapper = Wrapper.build(this, servletName, servletClass);
            // 将 wrapper 追加至容器
            addChildren(urlPattern, wrapper);
        }
    }

    /**
     * 初始化并 wrapper ，加入映射池中
     *
     * @param servletName
     * @param servletClass
     * @throws Exception
     */
    void addWrapper(String servletName, String servletClass) throws Exception {
        // 构造 wrapper 实例
        Wrapper wrapper = Wrapper.build(this, servletName, servletClass);
        // 加入窗口
        addChildren(servletName, wrapper);
    }
}
